<template>
  <div class="box route-page">
    <section class="header">
      <a-page-header
        title="新建收据"
        @back="goBack"
        style="padding: 6px 12px"
      >
        <template #backIcon>
          <close-outlined v-if="$route.query.isClose"/>
          <arrow-left-outlined v-else/>
        </template>
      </a-page-header>
    </section>
    <section class="content">
      <div class="content-box">
        <a-table
          :columns="columns"
          :dataSource="dataSource"
          rowKey="id"
          :row-selection="rowSelection"
          :scroll="{ x: 'max-content' }"
          :pagination="false"
        >
          <template #title>
            <a-row type="flex" align="middle" justify="space-between">
              <a-col flex="auto">
                <span class="title">申请开据的收据</span>
              </a-col>
              <a-col class="ml-10">
                <a-button type="primary" ghost @click="merge">合并开据</a-button>
              </a-col>
              <a-col class="ml-10">
                <a-button type="primary" @click="generateNumber"
                  >生成收据编号</a-button
                >
              </a-col>
            </a-row>
            <a-alert
              class="mt-10"
              type="info"
              show-icon
              v-if="selectedtList.length"
            >
              <template #message>
                <span>已选择</span>
                <span class="mlr-5 text-blue">{{ selectedtList.length }}</span>
                <span>项</span>
                <span class="ml-10">金额合计：{{ applyMoneyTotal }}</span>
                <span>元</span>
              </template>
            </a-alert>
          </template>
          <template #bodyCell="{ text, record, index, column }">
            <template v-if="column.key === 'apply_receipt_amount'">
              <div>
                <a-input-number
                  v-model:value="record.apply_receipt_amount"
                  :min="0"
                  @blur="inputBlur(record)"
                  :max="Number(record.unreceipt_amount)"
                  :precision="2"
                  class="w-100p"
                  :disabled="record.applyInvoiceAmountDisabled"
                />
              </div>
            </template>
            <template v-if="column.key === 'Payee'">
              <a-select
                v-if="record.sellerAccount && record.sellerAccount.length > 0"
                v-model:value="record.collection_company_id"
                @change="(value) => handleTaxRateChange(value, record, index)"
                style="width: 120px"
              >
                <a-select-option
                  v-for="item of record.sellerAccount"
                  :key="item.id"
                  :value="item.id"
                >
                  {{ item.company_name }}
                </a-select-option>
              </a-select>
            </template>
            <template v-if="column.key === 'receipt_number'">
              <span v-if="record.receipt_number">{{
                record.receipt_number
              }}</span>
              <span v-else>未生成</span>
            </template>
            <template v-if="column.key === 'action'">
              <a-button
                type="link"
                @click="splitClick"
                v-if="record.applyInvoiceAmountDisabled"
                >拆分</a-button
              >
              <a-button type="link" @click="editClick(record)">编辑</a-button>
            </template>
          </template>
        </a-table>
      </div>
      <div class="footer">
        <a-space>
          <a-button @click="goBack">取消</a-button>
          <a-button type="primary" @click="btnSubmit">确定</a-button>
        </a-space>
      </div>
    </section>
    <EditReceipt
      :visible="visible"
      @onClose="closeClick"
      @success="successData"
      :id="idEdit"
      :content="contentEdit"
    />
  </div>
</template>

<script>
import { defineComponent, reactive, toRefs, computed, ref, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import request from "../../../common/utils/request";
import { message } from "ant-design-vue";
import utils from "../../../common/utils/utils";
import EditReceipt from "./modules/editReceipt.vue";
import { CloseOutlined , ArrowLeftOutlined} from '@ant-design/icons-vue';


export default defineComponent({
  name: "receipt",
  components: { EditReceipt, CloseOutlined , ArrowLeftOutlined },
  setup() {
    const $router = useRouter();
    const $route = useRoute();
    const goBack = () => {
      if (window?.microApp?.getData()?.isMainDrawer) {
        window?.microApp?.getData()?.closeDrawer();
      }else{
        $router.back();
      }
    };
    const columns = [
      {
        title: "交款单位",
        dataIndex: "owner_name",
      },
      {
        title: "收据编号",
        dataIndex: "receipt_number",
        key: "receipt_number",
      },
      {
        title: "可开据金额",
        dataIndex: "unreceipt_amount",
      },
      {
        title: "申请开据金额",
        dataIndex: "apply_receipt_amount",
        key: "apply_receipt_amount",
        width: 200,
      },
      {
        title: "费用类型",
        dataIndex: "cost_type_txt",
      },
      {
        title: "收款单位",
        dataIndex: "Payee",
        key: "Payee",
      },
      {
        title: "备注",
        dataIndex: "remark",
      },
      {
        title: "操作",
        dataIndex: "action",
        key: "action",
        fixed: "right",
      },
    ];

    const state = reactive({
      visible: false,
      idEdit: "",
      contentEdit: {},
      dataSource: [],
      billIds: [],
      applicationValue: {},
      selectedtList: "",
      receiptNos: [],
      selectedRowKeys: [],
      applyValue: "", //申请开据金额
      applyMoneyTotal: 0, //申请开据金额合计
      disabledCombine: false,
    });

    const ids = $route.query.billIds;
    const receiptList = () => {
      request
        .post("/org", "/receipt/lssue", { billIds: ids.split(",") })
        .then((res) => {
          state.dataSource = res.list;
          state.dataSource.forEach((item) => {
            item.apply_receipt_amount = item.unreceipt_amount;
            // 收款字段处理
            if (item.sellerAccount && item.sellerAccount.length) {
              item.collection_company_id = item.sellerAccount[0].id;
              item.collection_company = item.sellerAccount[0].company_name;
              item.collection_uname = item.sellerAccount[0].seller_name;
              item.collection_phone = item.sellerAccount[0].phone;
              item.collection_address = item.sellerAccount[0].address;
            }
          });
          setTimeout(()=>{
            onSelectedRowChange(state.dataSource.map((item)=>item.id), state.dataSource)
            if($route.query.stream_id){
              // 如果有流水ID 就自动合并且生成收据编号
              streamIdChange()
            }
          },50)
        });
    };
    receiptList();


    /* 选择账单行 */
    const rowSelection = computed(() => ({
      selectedRowKeys: state.selectedRowKeys,
      onChange: onSelectedRowChange,
    }));
    const onSelectedRowChange = (selectedRowKeys, selectedRows) => {
      state.selectedtList = selectedRows;
      state.selectedRowKeys = selectedRowKeys;
      let total = 0;
      state.disabledCombine = false;
      state.selectedtList.forEach((item, index) => {
        total = (Number(total) + Number(item.unreceipt_amount)).toFixed(2);
        if (
          index > 0 &&
          !state.disabledCombine &&
          item.owner_id != state.selectedtList[index - 1].owner_id
        ) {
          state.disabledCombine = true;
        }
      });
      state.applyMoneyTotal = total;
    };

    // 生成编号
    const generateNumber = () => {
      if (!state.selectedtList.length) {
        message.warning("请勾选后再进行操作");
        return;
      }

      let receipt_number = [];
      let idList = [];
      let buildIdList = []
      if(contextData.value.length > 0){
        // 合并的
          contextData.value.forEach((item)=>{
            if(item.splitList){
              item.splitList.forEach((receiptData)=>{
                if(receiptData.build_id) {
                  buildIdList.push(receiptData.build_id) 
                }
              })
            }
        })
      }else{
        // 未合并的
        buildIdList = state.selectedtList.filter((item)=>item.build_id).map((build)=>build.build_id)
      }
      request
        .get("/org", "/receipt/buildNumber", {
          build_id: buildIdList[0],
          village_id: state.selectedtList[0].village_id,
          num: state.selectedtList.length,
        })
        .then((res) => {
          receipt_number = res.receiptNos.map((item) => {
            return item;
          });

          // for (let key in state.selectedtList) {
          //   state.selectedtList[key]["receipt_number"] =
          //     receipt_number[key].receipt_number;
          //   state.selectedtList[key]["receipt_int"] =
          //     receipt_number[key].receipt_int;
          // }
          state.selectedtList.forEach((item, indexList) => {
            receipt_number.forEach((data, index) => {
              if (index == indexList) {
                item.receipt_number = data.receipt_number;
                item.receipt_int = data.receipt_int;
                idList.push(item.id);
              }
            });
          });

          let dataList = state.dataSource.filter((item) => {
            if (!idList.includes(item.id)) {
              return true;
            }
          });
          dataList.forEach((item) => {
            state.dataSource.forEach((data) => {
              if (item.id == data.id) {
                data.receipt_number = undefined;
                data.receipt_int = undefined;
              }
            });
          });

          contextData.value.forEach((item) => {
            state.selectedtList.forEach((data) => {
              item.receipt_int = data.receipt_int;
              item.receipt_number = data.receipt_number;
            });
          });
        });
    };
    const selectId = ref(0);
    const handleTaxRateChange = (value, record, index) => {
      selectId.value = value;
      let sellerAccountData = record.sellerAccount.find(
        (item) => item.id == value
      );
      if (sellerAccountData) {
        record.collection_company_id = sellerAccountData.id;
        record.collection_company = sellerAccountData.company_name;
        record.collection_uname = sellerAccountData.seller_name;
        record.collection_phone = sellerAccountData.phone;
        record.collection_address = sellerAccountData.address;
      }

      // 合并后处理
      if (contextData.value.length) {
        contextData.value.forEach((item) => {
          if (item.payment_company_id == record.owner_id) {
            item.collection_company_id = sellerAccountData.id;
            item.collection_company = sellerAccountData.company_name;
            item.collection_uname = sellerAccountData.seller_name;
            item.collection_phone = sellerAccountData.phone;
            item.collection_address = sellerAccountData.address;
          }
        });
      }
      state.dataSource.forEach((item) => {
        if (item.id == value) {
          item.build_id = value;
        }
      });
    };

    // 获取申请开据金额 输入框
    const inputBlur = (record) => {
      if (record.apply_receipt_amount == 0) {
        message.warn("申请开据金额不可小于0");
        record.apply_receipt_amount = Number(record.unreceipt_amount);
      }
      // if (
      //   Number(record.unreceipt_amount) !== Number(record.apply_receipt_amount)
      // ) {
      //   record.unreceipt_amount = String(record.apply_receipt_amount) + ".00";
      // }
    };

    let dataList = ref([]); //存储合并数据
    let selectList = ref({});
    let splitList = [];
    let contextData = ref([]);
    let mergeObject = ref({});
    let mergeList = ref([]);
    // 合并
    const merge = () => {
      if (state.selectedtList.length <= 1) {
        return;
      }
      if (state.disabledCombine) {
        message.warn("只有选择相同交款方才能合并开据~");
        return;
      }
      utils.modalConfirm({
        content: "是否确认合并？合并操作会重置已生成的收据编号",
        onOk: () => {
          mergeHandle()
        },
      });
    };

    const mergeHandle=()=>{
      let sum = 0;
      let text = "";
      let objectSplit = {};
      let buil_ids = [];
      let subbill_ids = [];
      let obejct = {};
      state.selectedtList.forEach((item, selecteIndex) => {
        if (selecteIndex != 0) {
          dataList.value = dataList.value.concat(item);
          state.dataSource.forEach((data) => {
            data.receipt_number = undefined;
            data.receipt_int = undefined;
          });
          state.dataSource = state.dataSource.filter(sourceItem => sourceItem.id !== item.id);
          state.selectedtList = state.selectedtList.filter(sourceItem => sourceItem.id !== item.id);
        }
      });
      if (dataList.value) {
        state.selectedtList.forEach((item, index) => {
          if (index == 0) {
            let build = [];
            selectList.value.unreceipt_amount = item.unreceipt_amount;
            selectList.value.apply_receipt_amount =
              item.apply_receipt_amount;
            selectList.value.cost_type_txt = item.cost_type_txt;

            dataList.value.forEach((data) => {
              sum = (Number(sum) + Number(data.unreceipt_amount)).toFixed(
                2
              );
              text = text + data.cost_type_txt + ",";
              // item.bill_id.push(data.bill_id);
              objectSplit = {
                bill_id: data.bill_id,
                build_id: data.build_id,
                subbill_id: data.id,
                can_receipt_amount: data.unreceipt_amount,
                cost_type: data.cost_type,
                apply_receipt_amount: data.apply_receipt_amount,
              };
              console.log(data);
              buil_ids = buil_ids.concat(data.bill_id);
              subbill_ids = subbill_ids.concat(data.id);
              mergeList.value = mergeList.value.concat(objectSplit);
            });
            sum = (Number(sum) + Number(item.unreceipt_amount)).toFixed(2);
            item.unreceipt_amount = sum;
            item.apply_receipt_amount = sum;
            item.cost_type_txt = text + item.cost_type_txt;
            item.applyInvoiceAmountDisabled = true;
            buil_ids = buil_ids.concat(item.bill_id);
            subbill_ids = subbill_ids.concat(item.id);
            obejct = {
              bill_id: item.bill_id,
              build_id: item.build_id,
              subbill_id: item.id,
              can_receipt_amount: selectList.value.unreceipt_amount,
              cost_type: item.cost_type,
              apply_receipt_amount: selectList.value.apply_receipt_amount,
            };
            mergeList.value = mergeList.value.concat(obejct);
            // item.bill_ids = buil_ids;
            // item.subbill_ids = subbill_ids;

            mergeObject.value = {
              payment_company_id: item.owner_id,
              payment_company: item.owner_name,
              payment_uname: item.payment_uname
                ? item.payment_uname
                : item.paymentAccount.contacter.name,
              payment_address: item.payment_address
                ? item.payment_address
                : item.paymentAccount.contacter.address,
              payment_phone: item.payment_phone
                ? item.payment_phone
                : item.paymentAccount.contacter.phone,

              // 收款
              collection_company: item?.collection_company,
              collection_company_id: item?.collection_company_id,
              collection_uname: item?.collection_uname,
              collection_address: item?.collection_address,
              collection_phone: item?.collection_phone,

              receipt_number: item.receipt_number, //收据编号
              receipt_int: item.receipt_int, //收据编号
              can_receipt_amount: item.unreceipt_amount, //开据金额
              apply_receipt_amount: item.apply_receipt_amount, //申请开据金额
              rule_id: item.rule_id,
              build_id: item.build_id,
              remark: item.remark, //备注
              cost_name: item.cost_name || item.cost_type_txt, //费用类型
              cost_type: item.cost_type, //费用类型
              bill_ids: buil_ids,
              subbill_ids: subbill_ids,
              remit_type: item.remit_type, //汇款方式

              splitList: mergeList.value,
            };
            // item.bill_id = buil_ids;
            contextData.value = contextData.value.concat(mergeObject.value);
            console.log("合并后", contextData.value,);
          }
        });
      }
    }

    // 拆分
    const splitClick = () => {
      state.selectedtList.forEach((item, index) => {
        if (index == 0) {
          item.unreceipt_amount = selectList.value.unreceipt_amount;
          item.apply_receipt_amount = selectList.value.apply_receipt_amount;
          item.cost_type_txt = selectList.value.cost_type_txt;
          item.applyInvoiceAmountDisabled = false;
        }
      });
      state.dataSource = state.dataSource.concat(dataList.value);
      state.selectedtList.length = 0;
      state.selectedRowKeys = [];
      contextData.value = [];
      mergeList.value = [];
      dataList.value = [];
      dataListSubmit = [];
    };

    // 编辑
    const editClick = (content) => {
      console.log(content, "编辑");
      // content.selectId = selectId.value || content.sellerAccount[0].id;
      if (content.bill_id.length) {
        state.idEdit = [...content.bill_id];
      } else {
        state.idEdit = [content.bill_id];
      }
      state.visible = true;
      state.contentEdit = content;
    };
    const closeClick = () => {
      state.visible = false;
      selectId.value = 0;
    };
    // 保存关闭
    const successData = (data) => {
      selectId.value = 0;
      state.visible = false;
      console.log(data, "保存");
      state.dataSource.forEach((item) => {
        if (item.id == data.id) {
          item.apply_receipt_amount = data.apply_receipt_amount;
          item.cost_name = data.expenseName;
          item.remark = data.remark;
          item["receipt_number"] = data.receiptNumber;
          item.issuer_time = data.issuingDate;
          item.remit_type = data.remit_type.join(",");
          // 交款
          item.payment_company = data.paymentUnit;
          item.payment_uname = data.payer;
          item.payment_address = data.address;
          item.payment_phone = data.phone;
          // 收款
          item.collection_company_id = data.payee;
          item.collection_company = data.collection_company;
          item.collection_uname = data.payeePeople;
          item.collection_phone = data.payeePhone;
          item.collection_address = data.payeeAddress;
          item.sellerAccount.forEach((account) => {
            if (account.id == data.payee) {
              account.address = data.payeeAddress;
              account.phone = data.payeePhone;
            }
          });

          // 合并后的
          if (contextData.value) {
            contextData.value.forEach((item) => {
              item.payment_company = data.paymentUnit;
              item.payment_uname = data.payer;
              item.payment_address = data.address;
              item.payment_phone = data.phone;
              // 收款
              item.collection_company_id = data.payee;
              item.collection_company = data.collection_company;
              item.collection_uname = data.payeePeople;
              item.collection_phone = data.payeePhone;
              item.collection_address = data.payeeAddress;

              item.receipt_number = data.receiptNumber;
              item.remit_type = data.remit_type.join(",");
              item.apply_receipt_amount = data.apply_receipt_amount;
              item.cost_name = data.expenseName;
              item.remark = data.remark;
              item.issuer_time = data.issuingDate;
            });
          }
        }
      });
    };

    // 关闭页面
    let receipt_json = [];
    let data = [];
    let total = 0;
    let dataListSubmit = [];
    let totalList = 0;
    let successSubmit = ref(false);
    const btnSubmit = () => {
      if (state.selectedtList.length < 1) {
        message.warn("必须选择至少一条对其进行操作~");
        return;
      }

      state.selectedtList.forEach((item) => {
        if (item.receipt_number) {
          successSubmit.value = true;
          if (contextData.value.length == 0) {
            total = (Number(total) + Number(item.apply_receipt_amount)).toFixed(
              2
            );
            splitList = {
              bill_id: item.bill_id,
              build_id: item.build_id,
              village_id: item.village_id,
              subbill_id: item.id,
              can_receipt_amount: item.unreceipt_amount,
              cost_type: item.cost_type,
              apply_receipt_amount: item.apply_receipt_amount,
            };
            dataListSubmit = {
              // 交款
              payment_company_id: item.owner_id,
              payment_company: item.owner_name,
              payment_uname: item.payment_uname
                ? item.payment_uname
                : item.paymentAccount.contacter.name,
              payment_address: item.payment_address
                ? item.payment_address
                : item.paymentAccount.contacter.address,
              payment_phone: item.payment_phone
                ? item.payment_phone
                : item.paymentAccount.contacter.phone,

              issuer_time: item.issuer_time,

              // 收款
              collection_company: item?.collection_company,
              collection_company_id: item?.collection_company_id,
              collection_uname: item?.collection_uname,
              collection_address: item?.collection_address,
              collection_phone: item?.collection_phone,

              receipt_number: item.receipt_number, //收据编号
              receipt_int: item.receipt_int, //收据编号
              can_receipt_amount: item.unreceipt_amount, //开据金额
              apply_receipt_amount: item.apply_receipt_amount, //申请开据金额
              rule_id: item.rule_id,
              build_id: item.build_id,
              village_id: item.village_id,
              remark: item.remark, //备注
              cost_name: item.cost_name ? item.cost_name : item.cost_type_txt, //费用名称
              cost_type: item.cost_type, //费用类型
              bill_ids: [item.bill_id],
              subbill_ids: [item.id],
              remit_type: item.remit_type, //汇款方式
            };

            data = dataListSubmit;
            data.splitList = [splitList];
            receipt_json.push(data);
          } else {
            total = 0;
            totalList = 0;
            receipt_json = [];
            receipt_json = contextData.value;
            contextData.value.forEach((item) => {
              total = Number(item.can_receipt_amount);
              totalList = item.bill_ids.length;
            });
            // total = Number(contextData.value.unreceipt_amount).toFixed(2);
          }
        } else {
          receipt_json = [];
          successSubmit.value = false;
        }
      });
      if (!successSubmit.value) {
        message.warn("请生成编号再进行开据");
      } else {
        // 判断是否有收款单位
        let isCollectionList = [];
        isCollectionList = receipt_json.filter(
          (receipt) => receipt.collection_company_id
        );
        if (!isCollectionList.length) {
          message.warn("请设置收款单位后再开收据");
          return;
        }
        let parmas = {};
        parmas.receipt_json = receipt_json;
        parmas.choose_num = totalList ? totalList : receipt_json.length;
        parmas.choose_amount = Number(total);
        if ($route.query.stream_id) {
          parmas.stream_id = $route.query.stream_id
        
        }
        console.log(parmas, "parmas");
        request
          .post("/org", "/receipt/saveLssue", parmas)
          .then((res) => {
            console.log(res);
            message.success("提交成功");
            if(res.group_key){
              window.microApp.forceDispatch({
                  type: "SetChildDrawerList",
                  info: {
                    props: {
                      title: null,
                      maskCloseable: true,
                      visible: true,
                      closable: false,
                      width: 1200,
                      bodyStyle: {height: '100%',},
                      destroyOnClose: true,
                    },
                    microId: "org_receipt_detail",
                    heightFull: true,
                    app: "org",
                    url: `/bill/receiptDetail?group_key=${res.group_key}&isClose=true`,
                    params: {
                      isMainDrawer: true,
                    }
                  },
                })
            }
            if (window?.microApp?.getData()?.isMainDrawer) {
              window?.microApp?.getData()?.closeSubmitDrawer();
            }
            setTimeout(() => {
              console.log("返回");
              goBack();
            }, 200);
          })
          .catch(() => {
            receipt_json = [];
          });
      }
    };

    const streamIdChange = () =>{
      if (state.selectedtList.length>1) {
        mergeHandle()
        generateNumber()
      }else{
        generateNumber()
      }
    }

    return {
      columns,
      rowSelection,
      goBack,
      ...toRefs(state),
      generateNumber,
      handleTaxRateChange,
      inputBlur,
      merge,
      splitClick,
      editClick,
      closeClick,
      successData,
      btnSubmit,
    };
  },
});
</script>

<style lang="less" scoped>
.box {
  .header {
    background-color: #fff;
  }
  .content {
    padding: 10px;
    width: 100%;
    height: 87%;
    .content-box {
      width: 100%;
      height: 100%;
      background-color: #fff;
      overflow-y: auto;

      .title {
        font-size: 20px;
        font-weight: 600;
      }
    }
  }
  .footer {
    text-align: right;
    padding-top: 20px;
  }
}
</style>
